 layui.use(['form', 'table', 'jquery'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;


        //删除单个
        function delone(pk) {
            $.ajax({
                url: 'http://127.0.0.1:8000/user/user/' + pk + '/',
                type: 'DELETE',
                headers: {
                        'Authorization': localStorage.getItem('token')
                    },
                success: function (result) {
                    layer.msg(result.message, {icon: 1, time: 1000});
                    layui.table.reload('currentTableId');
                }
            })
        }

        // 删除多个
        function delmult(pk) {
            $.ajax({
                url: 'http://127.0.0.1:8000/user/user/' + pk + '/',
                type: 'POST',
                headers: {
                        'Authorization': localStorage.getItem('token')
                    },
                success: function (result) {
                    layer.msg(result.message, {icon: 1, time: 1000});
                    layui.table.reload('currentTableId');
                }
            })
        }


        //查询后渲染页面
        function render(url) {
            table.render({
                    elem: '#currentTableId',
                    url: url,
                    headers: {
                        'Authorization': localStorage.getItem('token')
                    },
                    toolbar: '#toolbarDemo',
                    page: true,
                    limit: 10,
                    limits: [10],
                    height: 600,
                    even: true,
                    size: 'md',
                    totalRow: true,
                    curr: 1,
                    defaultToolbar: ['filter', 'exports', 'print', {
                        title: '提示',
                        layEvent: 'LAYTABLE_TIPS',
                        icon: 'layui-icon-tips'
                    }],
                    parseData: function (res) {
                        return {

                            "code": res.status === 200 ? 0 : 500, //解析接口状态
                            "msg": res.message, //解析提示文本
                            "count": res.page.count, //解析数据长度
                            "data": res.page.results,
                            "curr": res.page.pageNum
                        }
                    },
                    cols: [[
                        {type: "checkbox"},
                        {field: 'id', title: 'ID', sort: true, align: "center"},
                        {field: 'username', title: '用户名', align: "center"},
                        {
                            field: 'gender', title: '性别', align: "center", templet: function (d) {
                                // 如果性别为M，显示男，性别为F，显示女
                                return d.gender === 'M' ? '男' : '女'
                            }
                        },
                        {field: 'email', title: '邮箱', align: "center"},
                        {field: 'phone', title: '电话', align: "center"},
                        {field: 'occupation', title: '职业', align: "center"},
                        {field: 'Remarks', title: '备注信息', align: "center"},
                        {
                            field: 'date_joined',
                            align: "center",
                            title: '创建时间',
                            sort: true,
                            templet: function (d) {
                                return layui.util.toDateString(d.date_joined, 'yyyy-MM-dd HH:mm:ss')
                            }
                        },
                        {title: '操作', toolbar: '#currentTableBar', align: "center"},
                    ]]
                }
            );
        }

        // 表格渲染
        render('http://localhost:8000/user/user/')
        //重置刷新页面
        form.on('submit(data-reset-btn)', function (data) {
            // 执行重置操作
            window.location.reload();
        })

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var uname = data.field.username;
            var email = data.field.email;
            if (uname === '' && email === '') {
                layer.msg('请输入用户名或邮箱')
            } else if (email === '') {
                $.ajax({
                    url: 'http://127.0.0.1:8000/user/user/cat/' + uname + '/',

                    type: 'get',
                    headers: {
                        'Authorization': localStorage.getItem('token')
                    },
                    dataType: 'json',
                    success: function (res) {
                        //渲染表格

                        render('http://127.0.0.1:8000/user/user/cat/' + uname + '/')
                    }
                })
            } else if (uname === '') {
                $.ajax({
                    url: 'http://127.0.0.1:8000/user/user/cat/' + email + '/',
                    type: 'get',
                    headers: {
                        'Authorization': localStorage.getItem('token')
                    },
                    dataType: 'json',
                    success: function (res) {
                        //渲染表格

                        render('http://127.0.0.1:8000/user/user/cat/' + email + '/')
                    }
                })
            }

            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加用户',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '../page/table/add.html',
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId');
                var data = checkStatus.data;
                var id = data[0].id;
                // 遍历data,拿到每个id
                var ids = data.map(item => item.id);
                if (checkStatus.isAll === true) {
                    layer.confirm('确定删除所有用户吗？', function (index) {
                        delmult(ids) //删除所有
                    })
                } else if (checkStatus.isAll === false) {
                    if (data.length === 1) {
                        layer.confirm('确定删除该用户吗？', function (index) {
                            delone(id) //删除单个
                        })
                    } else if (data.length > 1) {
                        layer.confirm('确定删除选中用户吗？', function (index) {
                            delmult(ids) //删除选中
                        })
                    }
                }
            }
        });


        table.on('tool(currentTableFilter)', function (obj) {
                var data = obj.data;
                if (obj.event === 'edit') {
                    var index = layer.open({
                        title: '编辑用户',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: ['100%', '100%'],
                        content: '../page/table/edit.html',
                        success: function (layero, index) {
                            var body = $(layero.find('iframe')[0].contentWindow.document); // 获取iframe的document对象
                            if (data.gender === 'M') {
                                $(body.find("input[type='radio']")).eq(0).prop("checked", true);
                            } else if (data.gender === 'F') {
                                $(body.find("input[type='radio']")).eq(1).prop("checked", true);
                            }
                            // 属性添加完要重新渲染
                            var form = layui.jquery('iframe')[0].contentWindow.layui.form;
                            form.render("radio");

                            body.find("#id").val(data.id);
                            body.find("#username").val(data.username);
                            body.find("#phone").val(data.phone);
                            body.find("#email").val(data.email);
                            body.find("#occupation").val(data.occupation);
                            body.find("#Remarks").val(data.Remarks);
                        },
                    });
                    $(window).on("resize", function () {
                        layer.full(index);
                    });
                    return false;
                } else if (obj.event === 'delete') {
                    var pk = data.id
                    layer.confirm('确定删除?', function (index) {
                        delone(pk) // 删除单个
                        layer.close(index);
                    });
                }
            }
        )
        ;

    });
